﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Runtime.InteropServices;
using System.Text;
using System.Xml;

namespace lcs.Web
{
    /// <summary>   
    /// Invoke server function and send data to client
    /// </summary>   
    public partial class aspx_Ajax : System.Web.UI.Page
    {
        //[DllImport("dog_auth_srv.dll", EntryPoint = "verifyDigest", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        //public static extern int verifyDigest(int ivendorid, int idogid, String strchlge, String strrspn, String strfctr);

        //[DllImport("dog_auth_srv_x64.dll", EntryPoint = "verifyDigest", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        //public static extern int verifyDigest_x64(int ivendorid, int idogid, String strchlge, String strrspn, String strfctr); 

        //public class DllInvoke
        //{
        //    [DllImport("kernel32.dll")]
        //    private extern static IntPtr LoadLibrary(String path);
        //    [DllImport("kernel32.dll")]
        //    private extern static IntPtr GetProcAddress(IntPtr lib, String funcName);
        //    [DllImport("kernel32.dll")]
        //    private extern static bool FreeLibrary(IntPtr lib);
        //    private IntPtr hLib;
        //    public DllInvoke(String DLLPath)
        //    {
        //        hLib = LoadLibrary(DLLPath);
        //    }
        //    ~DllInvoke()
        //    {
        //        FreeLibrary(hLib);
        //    }

        //    public Delegate Invoke(String APIName, Type t)
        //    {
        //        IntPtr api = GetProcAddress(hLib, APIName);
        //        return (Delegate)Marshal.GetDelegateForFunctionPointer(api, t);
        //    }
        //}

        // Dispatch
        public override void ProcessRequest(HttpContext context)
        {

            // Get function's name
            string methodName = context.Request.Params["func"];
            if (methodName == "Authentication")
            {
                this.Authentication(context);
                return;
            }
            else if (methodName == "getChallenge")
            {
                this.getChallenge(context);
                return;
            }
            else if (methodName == "getVendorID")
            {
                this.getVendorID(context);
                return;
            }
            else if (methodName == "getAuthCode")
            {
                this.getAuthCode(context);
                return;
            }
            else if (methodName == "getFctr")
            {
                this.getFactor(context);
                return;
            }
            else
            {
                context.Response.Write("Error");
                return;
            }
        }

        /// <summary>
        /// Authenticate string is match or not
        /// </summary>
        /// <param name="context"></param>
        private void Authentication(HttpContext context)
        {

        }

        /// <summary>
        /// Generate random string
        /// </summary>
        /// <param name="context"></param>
        private void getChallenge(HttpContext context)
        {
            String strChage = Guid.NewGuid().ToString().Replace("-", "").ToUpper();

            // save challenge string to session for later verification 
            Session.Add("LoginChallengeStr", strChage);

            context.Response.Write(strChage);
        }

        /// <summary>
        /// Get vendor id from server
        /// </summary>
        /// <param name="context"></param>
        private void getVendorID(HttpContext context)
        {
            String strVendorID = String.Empty;
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(Server.MapPath(".\\serverdata\\auth_code.xml"));
                XmlElement root = (XmlElement)xmlDoc.SelectSingleNode("//dogauth");
                if (null != root)
                {
                    XmlNodeList vendorNodes = root.GetElementsByTagName("vendor");
                    foreach (XmlNode node in vendorNodes)
                    {
                        strVendorID = ((XmlElement)node).GetAttribute("id");
                        context.Response.Write(strVendorID);
                        break;
                    }
                }
                else
                {
                    context.Response.Write("The node root is not existed");
                }
            }
            catch (Exception e)
            {
                context.Response.Write(e.Message);
            }
        }

        /// <summary>
        /// Get auth code from server
        /// </summary>
        /// <param name="context"></param>
        private void getAuthCode(HttpContext context)
        {
            String strAuthCode = String.Empty;
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(Server.MapPath(".\\serverdata\\auth_code.xml"));
                XmlNode root = xmlDoc.SelectSingleNode("//dogauth");
                if (null != root)
                {
                    strAuthCode = (root.SelectSingleNode("authcode")).InnerText;
                    context.Response.Write(strAuthCode);
                }
                else
                {
                    context.Response.Write("The node root is not existed");
                }
            }
            catch (Exception e)
            {
                context.Response.Write(e.Message);
            }
        }

        /// <summary>
        /// Get authentication factor from server
        /// </summary>
        /// <param name="context"></param>
        private void getFactor(HttpContext context)
        {
            String strFctr = String.Empty;
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(Server.MapPath(".\\serverdata\\auth_factor.xml"));
                XmlNode root = xmlDoc.SelectSingleNode("//dogauth");
                if (null != root)
                {
                    strFctr = (root.SelectSingleNode("factor")).InnerText;
                    context.Response.Write(strFctr);
                }
                else
                {
                    context.Response.Write("The node root is not existed");
                }
            }
            catch (Exception e)
            {
                context.Response.Write(e.Message);
            }
        }
    }
}